package com.ccp.dev.form.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.table.TableModel;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.form.dao.FormDefTreeDao;
import com.ccp.dev.form.model.FormDef;
import com.ccp.dev.form.model.FormDefTree;
import com.ccp.dev.form.model.FormTable;
import net.sf.json.JSONObject;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * FORM_DEF_Tree service类
 *
 * @author chenjing
 */
@Service
public class FormDefTreeService extends BaseService<FormDefTree> {

    @Resource
    private FormDefTreeDao formDefTreeDao;

    @Resource
    private FormDefService formDefService;

    @Resource
    private FormTableService formTableService;

    @Resource
    JdbcTemplate jdbcTemplate;

    /**
     * 保存 form_def_tree 信息
     *
     * @param formDefTree formDefTree
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(FormDefTree formDefTree) {
        String id = formDefTree.getId();
        if (StringUtil.isEmpty(id)) {
            id = UUIDUtils.getUUIDFor32();
            formDefTree.setId(id);
            formDefTreeDao.add(formDefTree);
        } else {
            formDefTreeDao.update(formDefTree);
        }
    }

    /**
     * 根据formKey获取树形表单配置。
     * @param formKey formKey
     * @return FormDefTree
     */
    public FormDefTree getByFormKey(String formKey) {
        return  formDefTreeDao.getByFormKey(formKey);
    }

    /**
     * 获取JSON数据。
     * @param formKey formKey
     * @param params params
     * @return List<JSONObject>
     */
    public List<JSONObject> treeListJson(String formKey, Map<String, Object> params){
        FormDefTree formDefTree = getByFormKey(formKey);
        FormDef formDef = formDefService.getDefaultVersionByFormKey(formKey);
        FormTable formTable = formTableService.getOneById(formDef.getTableId());

        String sql=getSql(formDefTree, formTable, params);

        // 获取jdbcTemplate
        List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);

        List<JSONObject> jsonObjectList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            JSONObject jo=getJsonByMap(map);
            jsonObjectList.add(jo);
        }
        return jsonObjectList;
    }

    /**
     * 将parentId,id,name,isParent 进行转换
     *
     * @param map map
     * @return JSONObject
     */
    private JSONObject getJsonByMap(Map<String, Object> map){
        JSONObject jo = new JSONObject();
        for (String key : map.keySet()) {
            Object val=map.get(key) == null ? "" : map.get(key);
            //下面换大小写是为了处理oracle没大小写之分的状况
            if ("PARENTID".equals(key)) {
                jo.put("parentId", val);
                continue;
            }
            if("ID".equals(key)){
                jo.put("id", val);
                continue;
            }
            if("NAME".equals(key)){
                jo.put("name", val);
                continue;
            }
            if("ISPARENT".equals(key)){
                jo.put("isParent", val);
                continue;
            }
            if("DATAID".equals(key)){
                jo.put("dataId", val);
                continue;
            }
            jo.put(key, val);
        }
        return jo;

    }

    /**
     * 获取SQL语句。
     * @param formDefTree formDefTree
     * @param formTable formTable
     * @param params params
     * @return String
     */
    private String getSql(FormDefTree formDefTree,FormTable formTable,Map<String, Object> params){
        String treeIdField = formDefTree.getTreeId();
        String parentIdField = formDefTree.getParentId();
        String displayField = formDefTree.getDisplayField();
        StringBuffer stringBuffer = new StringBuffer();

        stringBuffer.append("select id dataId");
        stringBuffer.append("," + treeIdField + " id ");
        stringBuffer.append("," + parentIdField + " parentId ");
        stringBuffer.append("," + displayField + " name ");
        String tableName = TableModel.getCustomTableName(formTable.getTableName()) ;
        // 异步加载，需要返回isParent的值
        if (formDefTree.getLoadType().equals(FormDefTree.LOADTYPE_ASYNC)) {
            StringBuffer isParentSql = new StringBuffer();
            isParentSql.append("( case (select count(*)  from " + tableName + " p ");
            isParentSql.append("where p." + parentIdField + " = o." + treeIdField + " and p." + treeIdField + " != p." + parentIdField + ")");
            isParentSql.append("when 0 then 'false' else 'true' end )isParent ");
            stringBuffer.append("," + isParentSql);
        }

        stringBuffer.append("from " + tableName + " o ");

        // 异步加载，根据id查询
        if (formDefTree.getLoadType().equals(FormDefTree.LOADTYPE_ASYNC)) {
            String id = params.get("id").toString();
            if (StringUtil.isNotEmpty(id)) {
                stringBuffer.append("where " + parentIdField + " = " + id);
            } else {
                stringBuffer.append("where " + parentIdField + " = " + formDefTree.getRootId());
            }
        }
        return stringBuffer.toString();
    }
}
